package com.example.onlinereadingsystem.demos.web.filter;

import com.alibaba.fastjson.JSON;
import com.example.onlinereadingsystem.demos.web.dto.common.BaseContext;
import com.example.onlinereadingsystem.demos.web.enums.CommonConstant;
import com.example.onlinereadingsystem.demos.web.util.HttpUtil;
import com.example.onlinereadingsystem.demos.web.util.JwtTokenUtil;
import com.example.onlinereadingsystem.demos.web.util.Result;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Description 登录校验器
 * @Author ljm
 * @Date 2024/12/20
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    // 不需要登录的请求
    private static final String[] IGNORE_URI = {
            "/web/login/**",
            "/web/index/**",
            "/web/kind/**",
            "/web/novelReading/**",
            "/web/novelDetail/getNovelReadingDetail/*",
            "/web/novelDetail/getNovelMainComments",
            "/web/novelDetail/getNovelChildComments",
    };

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, JwtException {
        log.info("LoginCheckFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (Objects.equals(request.getMethod(), "OPTIONS")) {
            // log.info("method :" + method);
            filterChain.doFilter(request, response);
            return;
        }

        String requestURI = request.getRequestURI();
        boolean checkd = checkUri(requestURI);
//        String method = request.getMethod();
//        System.out.println("request:" + request);
        if (!checkd) {
            String token = request.getHeader("Access-Token");
            if (!Strings.isEmpty(token)) {
                try {
                    Claims claims = JwtTokenUtil.parseJwt(token);
                    BaseContext.setId(claims.get("userId").toString());
                    BaseContext.setUserName(claims.get("userName").toString());
                    filterChain.doFilter(request, response);
                    return;
                } catch (JwtException e) {
//                    handlerExceptionResolver.resolveException(request, response, null, e);
//                    response.getWriter().write(JSON.toJSONString(Result.error("用户未登录")));
//                    response.setHeader("Access-Control-Allow-Origin", "*");
                    HttpUtil.errorResponse(response, "token失效，请重新登录！", CommonConstant.SC_NO_AUTHZ);
                    return;
                }
            } else {
//                response.getWriter().write(JSON.toJSONString(Result.error("用户未登录")));
//                response.setHeader("Access-Control-Allow-Origin", "*");
                HttpUtil.errorResponse(response, "用户未登录！", CommonConstant.SC_NO_AUTHZ);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    private boolean checkUri(String url) {
        for (String notCheck : IGNORE_URI) {
            boolean check = PATH_MATCHER.match(notCheck, url);
            if (check) {
                return true;
            }
        }
        return false;
    }
}
